#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "signup.h"
#include "mainpage.h"
#include <QGraphicsDropShadowEffect>

QString MainWindow::userId=NULL;
QString MainWindow::userPassword=NULL;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QPixmap *pix = new QPixmap(":/mainphoto/zhuye.png");
    QSize sz = ui->label_image->size();
    ui->label_image->setPixmap(pix->scaled(sz));

    //设置图片阴影效果
    QGraphicsDropShadowEffect *shadow = new QGraphicsDropShadowEffect(this);
    shadow->setOffset(-3, 0);
    shadow->setColor(QColor("#888888"));
    shadow->setBlurRadius(30);
    ui->label_image->setGraphicsEffect(shadow);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void sqlite_Init()
{
    //添加SQLite数据库驱动
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");

    //设置数据库路径
    db.setDatabaseName("user.db");

    //dp.open()——打开数据库，数据库文件存在则连接，不存在则创建
    if(!db.open())
    {
        qDebug()<<"open error";
    }

    //执行语句query
    //创建表——QSqlQuery query.exec("create table (表的名字)")
    QString createsql=QString("create table if not exists user(id integer primary key autoincrement,"
                        "username ntext unique not NULL,"
                        "password ntext not NULL)");
    QSqlQuery query;
    if(!query.exec(createsql)){
        qDebug()<<"table create error";
    }
    else{
        qDebug()<<"table create success";
    }
}

void MainWindow::on_pushButton_signup_clicked()
{
    this->close();
    Signup *s = new Signup;
    s->show();
}

void MainWindow::on_pushButton_signin_clicked()
{
    sqlite_Init();
        QString username = ui->lineEdit_username->text();
        QString password = ui->lineEdit_password->text();

        //将arg（）括号里面的内容替换到'%1','%2'里面
        //例：select * from user where id=1
        //定位到id为1的用户数据
        QString sql=QString("select * from user where username='%1' and password='%2'")
                .arg(username).arg(password);

        //创建执行语句对象
        QSqlQuery query(sql);
        //判断执行结果
        if(!query.next())
        {
            qDebug()<<"Login error";
            QMessageBox::information(this,"登录认证","登录失败,账户或者密码错误");
        }
        else
        {
            qDebug()<<"Login success";
            QMessageBox::information(this,"登录认证","登录成功");
            MainWindow::userId=query.value(1).toString();
            MainWindow::userPassword=query.value(2).toString();
            //登录成功后可以跳转到其他页面
            Mainpage *w = new Mainpage;
            w->show();
            this->close();
        }
}
